<template>
	<view class="ring_search_wrap">
		<u-navbar
			:autoBack="false"
			title="搜索设备"
			bgColor="#030204"
			safeAreaInsetTop
			placeholder
			leftIconColor="#ffffff"
			@leftClick="back"
			titleStyle="{fontSize: 16px;font-weight: bold;color: #FFFFFF;}"
		>
			<view class="u-nav-slot f-base white" slot="right" style="color: white" @click="toRecordPage">
				<u-icon name="plus" color="#FFFFFF" size="24"></u-icon>
			</view>
		</u-navbar>

		<view>连接戒指，开启健康生活</view>
		<view>收到戒指后，需将戒指放在充电盒内 充电激活后连接！</view>

		<!-- <button type="primary" @click="checkPerm">检测权限</button>
		<br />
		<button type="primary" @click="getBle">获取蓝牙状态</button> -->

		<br />
		<button type="primary" @click="initBlue">初始化蓝牙</button>
		<button type="primary" @click="closeBlue">关闭蓝牙</button>

		<br />
		<br />

		<button type="primary" @click="searchDevice">搜索设备</button>

		<br />
		<br />
		<button type="primary" @click="connectDevice">连接设备</button>
		<button type="primary" @click="disconnectDevice">断开设备</button>

		<br />
		<br />
		<!-- <button type="primary" @click="time">对时</button> -->
		<button type="primary" @click="done">下发指令</button>

		<br />
		<br />

		<view>蓝牙状态：{{ bluetoothStateDesc }}</view>
		<view>搜索类型：{{ searchTypeDesc }}</view>
		<view>搜索状态：{{ searchStatusDesc }}</view>
		<br /><br /><br />
		<view>
			<view>设备列表</view>
			<view v-for="(item, index) in deviceList" :key="index">
				名称： {{ item.name || item.localName }}<br />
				地址：{{ item.mac }}
			</view>
		</view>
	</view>
</template>

<script>
import LOG4J from "../../common/utils/Log4j";
import { mapGetters, mapState } from "vuex";
import getProtocolMethodsByType from "@/js_sdk/bluetooth/protocol/index.js";
const protocol = getProtocolMethodsByType();
console.log("protocol", protocol);

const log4j = LOG4J.getLogCat("ring/search");
// log4j.log("这个是一个页面")
// log4j.error("这个是第二个页面", bleManage.getters.searchType)

export default {
	data() {
		return {};
	},
	computed: {
		...mapGetters("bleManage", ["deviceList", "bluetoothStateDesc", "searchTypeDesc", "searchStatusDesc", "needOpenBluetooth", "linkComplete"]),
	},

	watch: {
		linkComplete(nv) {
			console.log("连接已完成", nv);
		},
	},
	methods: {
		time() {
			protocol.setTime();
		},
		done() {
			// 49:59:95:B3:69:56

			const deviceId = "49:59:95:B3:69:56";
			// 引入 Android 类
			var BluetoothManager = plus.android.importClass("android.bluetooth.BluetoothManager");
			var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
			var BluetoothGatt = plus.android.importClass("android.bluetooth.BluetoothGatt");
			var BluetoothGattCallback = plus.android.importClass("android.bluetooth.BluetoothGattCallback");

			// 获取 Android 上下文
			var context = plus.android.runtimeMainActivity();

			// 获取 BluetoothManager 实例
			var bluetoothManager = context.getSystemService(context.BLUETOOTH_SERVICE);
			var bluetoothAdapter = bluetoothManager.getAdapter();

			// 检查 BluetoothAdapter 是否可用
			if (!bluetoothAdapter) {
				console.error("BluetoothAdapter 不可用");
				return;
			}

			// 获取设备
			var device = bluetoothAdapter.getRemoteDevice(deviceId);

			// 检查设备是否有效
			if (!device) {
				console.error("设备无效，无法连接");
				return;
			}

			// 连接到设备
			var gatt = device.connectGatt(
				plus.android.runtimeMainActivity(),
				false,
				new BluetoothGattCallback({
					onConnectionStateChange: function (gatt, status, newState) {
						if (newState === BluetoothGatt.STATE_CONNECTED) {
							console.log("设备已连接");
							gatt.discoverServices();
						} else if (newState === BluetoothGatt.STATE_DISCONNECTED) {
							console.log("设备已断开连接");
						}
					},
					onServicesDiscovered: function (gatt, status) {
						if (status === BluetoothGatt.GATT_SUCCESS) {
							console.log("服务发现成功");
							// 这里可以获取服务和特征
						}
					},
				})
			);

			// if (!this.deviceList.length) return;
			// const device = this.deviceList[0];
			// console.log("device mac", device);

			// try {
			// 	uni.getBLEDeviceCharacteristics({
			// 		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			// 		deviceId: device.deviceId,
			// 		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			// 		serviceId: "5833FF01-9B8B-5191-6142-22A4536EF123",
			// 		success(res) {
			// 			console.log("device getBLEDeviceCharacteristics:", res);
			// 		},
			// 		fail(error) {
			// 			console.log("device getBLEDeviceCharacteristics fail", error);
			// 		}
			// 	});

			// 	// uni.writeBLECharacteristicValue({
			// 	// 	deviceId: device.deviceId,
			// 	// 	serviceId: this.$store.state.bleManage.characteristics.service, // 主服务id
			// 	// 	characteristicId: this.$store.state.bleManage.characteristics.write, // 写入id
			// 	// 	value: new Uint8Array([0x01, 0x02]),
			// 	// 	success: (result) => {
			// 	// 		console.log("转换boot success", result);
			// 	// 	},
			// 	// 	fail: (result) => {
			// 	// 		console.log("转换boot fail", result);
			// 	// 	},
			// 	// });
			// } catch (error) {
			// 	console.log("转换boot error", error);
			// }

			// 时间
			// protocol.getTime()
			// protocol.setTime();

			// 版本
			// protocol.getSoftVersion();
			// setTimeout(() => {
			// 	protocol.getHardVersion();
			// }, 1000);

			// 电量
			// protocol.getBatteryLevel();
			// setTimeout(() => {
			// 	protocol.getBatteryCharing();
			// }, 1000);

			// 心率
			// protocol.testHeartRateHrv();

			// 血氧
			// protocol.testBloodOxygen();

			// 温度
			// protocol.testTemperature()

			// 当前步数
			// protocol.getRealTimeStep()

			// 历史记录
			// setTimeout(() => {
			// 	protocol.getHistoryData(true)
			// }, 1000);

			// 内存大小
			// setTimeout(() => {
			// 	protocol.getHistoryMemorySize();
			// }, 2000);

			// 周期
			// protocol.setPeriod(1 * 60);
			// setTimeout(() => {
			// 	protocol.getPeriod();
			// }, 1000);

			// 恢复出厂
			// protocol.factoryReset()
		},
		back() {
			uni.navigateBack({
				delta: 1,
			});
		},
		toRecordPage() {
			uni.navigateTo({
				url: "/pages/collection/myCollection",
			});
		},

		checkPerm() {
			this.$store.dispatch("bleManage/checkPermission");
		},

		getBle() {
			this.$store.dispatch("bleManage/getBluetoothAdapterState");
		},

		initBlue() {
			this.$store.dispatch("bleManage/initBluetooth");
		},
		closeBlue() {
			this.$store.dispatch("bleManage/closeBluetooth");
		},

		searchDevice() {
			this.$store.dispatch("bleManage/searchAllRingDevices");
			// this.$store.dispatch("bleManage/searchSpecifyRingDevice", "AA:30:A0:06:9A:D6");
		},

		connectDevice() {
			console.log("mapState", this.$store.state.bleManage.devices);

			if (!this.deviceList.length) return;
			this.$store.dispatch("bleManage/connectDevice", this.deviceList[0]);
		},
		disconnectDevice() {
			this.$store.dispatch("bleManage/disConnectDevice");
		},
	},
};
</script>

<style scoped lang="scss">
::v-deep.u-popup__content {
	background-color: transparent !important;
}

::v-deep .u-navbar__content__right {
	padding: 0 40rpx;
}
</style>
